package com.ruoyi.web.controller.basedata;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.basedata.domain.*;
import com.ruoyi.basedata.domain.vo.TerminalXbImportantTemplate;
import com.ruoyi.basedata.domain.vo.TerminalsXbProtocol;
import com.ruoyi.basedata.mapper.TerminalsXbMapper;
import com.ruoyi.basedata.service.ITerminalsXbService;
import com.ruoyi.basedata.service.IUsageRangeService;
import com.ruoyi.basedata.service.IXbCommandLogsService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.datastatistics.Agreement.GuoXinV1;
import io.swagger.v3.oas.annotations.Parameter;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 小档案Controller
 *
 * @author ruoyi
 * @date 2023-09-07
 */
@RestController
@RequestMapping("/basedata/terminalxb")
public class TerminalsXbController extends BaseController {
    @Autowired
    private ITerminalsXbService terminalsXbService;

    @Autowired
    private IXbCommandLogsService xbCommandLogsService;
    @Resource
    private Environment env;
    @Autowired
    private IUsageRangeService usageRangeService;

    @Autowired
    private TerminalsXbMapper terminalsXbMapper;

    @Value("${system-params.appKey}")
    public String appKey;
    //    @Value("${system-params.appSecret}")
    @Value("${system-params.appSecret}")
    private  String appSecret;
    @Value("${system-params.masterKey}")
    private  String masterKey;
    @Value("${system-params.productId}")
    private  String productId;


    @GetMapping("/listAll")
    public TableDataInfo listAll(TerminalsXb terminalsXb) {
        SysUser user = getLoginUser().getUser();
        if(user.getSystemFlag() != Constants.SYS_FLAG_ADMIN){
            terminalsXb.setTenantId(getLoginUser().getTenantId());
        }
        List<TerminalsXb> terminalsXbs1 = terminalsXbService.selectTerminalsXbListAll(terminalsXb);
        return getDataTable(terminalsXbs1);

    }



    /**
     * 查询小档案列表
     */
    @PreAuthorize("@ss.hasPermi('basedata:terminalxb:list')")
    @GetMapping("/list")
    public TableDataInfo list(TerminalsXb terminalsXb) {
        startPage();
        SysUser user = getLoginUser().getUser();
        if(user.getSystemFlag() != Constants.SYS_FLAG_ADMIN){
            terminalsXb.setTenantId(getLoginUser().getTenantId());
        }
        List<TerminalsXb> terminalsXbs1 = terminalsXbService.selectTerminalsXbList(terminalsXb);
        return getDataTable(terminalsXbs1);

    }
    /**
     * 查询小档案列表
     */
    @PreAuthorize("@ss.hasPermi('basedata:terminalxb:list')")
    @GetMapping("/gjList")
    public TableDataInfo gjList(TerminalsXb terminalsXb) {
        startPage();
        SysUser user = getLoginUser().getUser();
        if(user.getSystemFlag() != Constants.SYS_FLAG_ADMIN){
            terminalsXb.setTenantId(getLoginUser().getTenantId());
        }
        return getDataTable(terminalsXbMapper.selectTerminalsXbList(terminalsXb));

    }



    @PreAuthorize("@ss.hasPermi('basedata:terminalxb:list')")
    @GetMapping("/listForGJ")
    public TableDataInfo listForGJ(TerminalsXb terminalsXb) {
        startPage();
        SysUser user = getLoginUser().getUser();
        if(user.getSystemFlag() != Constants.SYS_FLAG_ADMIN){
            terminalsXb.setTenantId(getLoginUser().getTenantId());
        }
        return getDataTable(terminalsXbMapper.listForGJ(terminalsXb));

    }


    //根据区域编号获取该区域下所有小表信息包含子区域
//    @PreAuthorize("@ss.hasPermi('basedata:terminalxb:list')")
//    @Parameter(name = "areaCode", description = "区域编号", required = true, example = "1024")
//    @GetMapping("/listByAreaCode")
//    public TableDataInfo listByAreaId(@RequestParam("areaCode") String areaCode)
//    {
//        startPage();
//        List<TerminalsXb> list = terminalsXbService.selectTerminalsXbListByAreaId(areaCode);
//        return getDataTable(list);
//    }

    //查询待绑定的小表信息
    @PreAuthorize("@ss.hasPermi('basedata:terminalxb:list')")
    @GetMapping("/listNoBound")
    public TableDataInfo listNoBound() {
        startPage();
        List<TerminalsXb> list = terminalsXbService.selectlistNoBound();
        return getDataTable(list);
    }

    //绑定小表信息

    /**
     * 导出小档案列表
     */
    @PreAuthorize("@ss.hasPermi('basedata:terminalxb:export')")
    @Log(title = "小档案", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TerminalsXb terminalsXb) {
        List<TerminalsXb> list = terminalsXbService.selectTerminalsXbList(terminalsXb);
        ExcelUtil<TerminalsXb> util = new ExcelUtil<TerminalsXb>(TerminalsXb.class);
        util.exportExcel(response, list, "小档案数据");
    }

    /**
     * 获取小档案详细信息
     */
    @PreAuthorize("@ss.hasPermi('basedata:terminalxb:query')")
    @GetMapping(value = "/{ID}")
    public AjaxResult getInfo(@PathVariable("ID") Long ID) {
        return success(terminalsXbService.selectTerminalsXbByID(ID));
    }


    /**
     * 根据locationnb获取小档案详细信息
     */
    @PreAuthorize("@ss.hasPermi('basedata:terminalxb:query')")
    @GetMapping("getByLocationNb")
    public AjaxResult getInfo(@RequestParam("locationNb") String locationNb) {
        return success(terminalsXbService.getByLocationNb(locationNb));
    }
    /**
     * 新增小档案
     */
    @PreAuthorize("@ss.hasPermi('basedata:terminalxb:add')")
    @Log(title = "小档案", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody @Validated TerminalsXb terminalsXb) {

        String sign = null;
        try {

            String flag = terminalsXbService.insertTerminalsXb(terminalsXb);
            if (!"新增成功".equals(flag)) {
                return error(flag);
            }
//            if (terminalsXb.getConcentratorId() != null) {
//                return success("设备档案新增成功");
//            }
            if (null == terminalsXb.getProtocolId()) {
                return error("设备档案新增成功,协议错误，不能注册");
            }
            JSONObject responseBody = null;
            if (terminalsXb.getSignPlatform()==1){
                sign="AEP";
                responseBody = terminalsXbService.createGuoXinDeviceInAep(appKey, appSecret, masterKey, terminalsXb);
                if (responseBody==null)
                    return error(sign+"平台注册失败");
                if (Integer.parseInt(responseBody.getString("code")) == 0) {
                    String deviceId = JSONObject.parseObject(responseBody.getString("result")).getString("deviceId");
                    terminalsXb.setDeviceId(deviceId);
                    terminalsXbService.updateDeviceId(terminalsXb);
                    return success(sign+"平台注册成功");
                }
            }else if (terminalsXb.getSignPlatform()==2){
                sign="OneNET";
                responseBody = terminalsXbService.createDeviceInOneNet(terminalsXb);
                if (responseBody==null)
                    return error(sign+"平台注册失败");
                if (Integer.parseInt(responseBody.getString("errno")) == 0) {
                    String deviceId = responseBody.getJSONObject("data").getString("device_id");
                    terminalsXb.setDeviceId(deviceId);
                    terminalsXbService.updateDeviceId(terminalsXb);
                    return success(sign+"平台注册成功");
                }
            }else if (terminalsXb.getSignPlatform() == 3){
                //注册到netty
                terminalsXbService.updateDeviceId(terminalsXb);
                return success("netty平台注册成功");
            }
            return error("设备档案新增成功，"+sign+"平台注册失败");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return error("系统异常");
        }

    }

    /**
     * 修改小档案
     */
    @PreAuthorize("@ss.hasPermi('basedata:terminalxb:edit')")
    @Log(title = "小档案", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TerminalsXb terminalsXb) {
        try {
            TerminalsXb terminalsXb1 = terminalsXbService.selectTerminalsXbByID(terminalsXb.getId());
            boolean insertFlag = !terminalsXb1.getImei().equals(terminalsXb.getImei());
            String flag = terminalsXbService.updateTerminalsXb(terminalsXb);
            if (!flag.equals("更新成功")) {
                return error(flag);
            }
            if (insertFlag && terminalsXb.getProtocolId() != null && terminalsXb.getProtocolId().equals("2")) {
                JSONObject responseBody = terminalsXbService.createGuoXinDeviceInAep(appKey, appSecret, masterKey, terminalsXb);
                if (responseBody == null) {
                    return error("设备更新成功" + "AEP平台注册失败");
                }
                if (Integer.parseInt(responseBody.getString("code")) == 0) {
                    String deviceId = JSONObject.parseObject(responseBody.getString("result")).getString("deviceId");
                    terminalsXb.setDeviceId(deviceId);
                    terminalsXbService.updateTerminalsXb(terminalsXb);
                    return success("设备更新成功");
                }
                return error("设备更新成功" + "AEP平台注册失败" + responseBody.getString("msg"));
            }
            return success("设备更新成功");
        } catch (Exception e) {
            logger.error("更新户表档案异常",e);
            return error("系统异常");
        }

    }

    //销表
    @PreAuthorize("@ss.hasPermi('basedata:terminalxb:cancelTerminal')")
    @Log(title = "小表档案销表", businessType = BusinessType.UPDATE)
    @PutMapping("/cancelTerminal")
    public AjaxResult cancelTerminal(@RequestBody TerminalsXb terminalsXb) {
        boolean success = terminalsXbService.cancelTerminal(terminalsXb, this.getUsername());
        return success ? success("销表成功") : error("销表失败");
    }

//    //换表
    @PreAuthorize("@ss.hasPermi('basedata:terminalxb:changeTerminalXb')")
    @PostMapping("/changeTerminalXb")
    public AjaxResult changeTerminalXb(@RequestBody TerminalsXb terminalsXb)
    {
        boolean flag = terminalsXbService.changeTerminalXb(terminalsXb);
        if (flag){
            String sign = null;
            if (terminalsXb.getConcentratorId() != null) {
                return success("换表成功");
            }
            if (null == terminalsXb.getProtocolId() || !"2".equals(terminalsXb.getProtocolId())) {
                return error("换表成功,协议错误，不能注册");
            }
            JSONObject responseBody = null;
            if (terminalsXb.getSignPlatform()==1){
                sign="AEP";
                responseBody = terminalsXbService.createGuoXinDeviceInAep(appKey, appSecret, masterKey, terminalsXb);
                if (responseBody==null)
                    return error("换表成功," + sign+"平台注册失败");
                if (Integer.parseInt(responseBody.getString("code")) == 0) {
                    String deviceId = JSONObject.parseObject(responseBody.getString("result")).getString("deviceId");
                    terminalsXb.setDeviceId(deviceId);
                    terminalsXbService.updateDeviceId(terminalsXb);
                    return success("换表成功," +sign+"平台注册成功");
                }
            }else if (terminalsXb.getSignPlatform()==2){
                sign="OneNET";
                responseBody = terminalsXbService.createDeviceInOneNet(terminalsXb);
                if (responseBody==null)
                    return error("换表成功," +sign+"平台注册失败");
                if (Integer.parseInt(responseBody.getString("errno")) == 0) {
                    String deviceId = responseBody.getJSONObject("data").getString("device_id");
                    terminalsXb.setDeviceId(deviceId);
                    terminalsXbService.updateDeviceId(terminalsXb);
                    return success("换表成功," +sign+"平台注册成功");
                }
            }else if (terminalsXb.getSignPlatform() == 3){
                //注册到netty
                terminalsXbService.updateDeviceId(terminalsXb);
                return success("netty平台注册成功");
            }
            return error("换表成功，"+sign+"平台注册失败");
        }else {
            return error("换表失败");
        }
    }

    @PreAuthorize("@ss.hasPermi('basedata:terminalxb:edit')")
    @Log(title = "小档案", businessType = BusinessType.UPDATE)
    @Parameter(name = "id", description = "设备id", required = true, example = "1024")
    @PutMapping("/logout")
    public AjaxResult logout(@RequestParam(name = "id") Long id) {
        return toAjax(terminalsXbService.logout(id));
    }

    /**
     * 删除小档案
     */
    @PreAuthorize("@ss.hasPermi('basedata:terminalxb:remove')")
    @Log(title = "小档案", businessType = BusinessType.DELETE)
    @DeleteMapping("/{IDs}")
    public AjaxResult remove(@PathVariable Long[] IDs) throws Exception {
        return toAjax(terminalsXbService.deleteTerminalsXbByIDs(IDs));
    }

    //导入小表档案
    @Log(title = "小表管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<TerminalsXb> util = new ExcelUtil<TerminalsXb>(TerminalsXb.class);
        List<TerminalsXb> terminalsXbList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = terminalsXbService.importUser(terminalsXbList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/createCommand")//开关阀
    @PreAuthorize("@ss.hasPermi('basedata:termianlxb:terminalXbCommand')")
    public AjaxResult createCommand(@RequestParam(value = "commandType", required = false) Integer commandType,
                                    @RequestParam(value = "isOpen", required = false) String isOpen,
                                    TerminalsXbProtocol terminalsXbProtocol) {
        try {
            TerminalsXbProtocol terminalsXbProtocol1 = terminalsXbService.getcreateCommandParm(commandType, isOpen, terminalsXbProtocol);
            if (terminalsXbProtocol1 == null) {
                return error("该表协议不存在");
            }

            //解析命令
            byte[] valveControlData = GuoXinV1.getValveControlData(terminalsXbProtocol1.getCommunicateAddress(), isOpen);
            String payload = GuoXinV1.bytesToHexString(valveControlData);

            //设置请求body
            JSONObject jsonObject = new JSONObject();
            Map<String, Object> content = new HashMap<>();
            if (terminalsXbProtocol1.getSignPlatform() == 3){
                String communicationType = DictUtils.getDictLabel("communication_type", terminalsXbProtocol1.getCommunicationType());
                String url = env.getProperty("netty-url." + communicationType + "." + "requestNetty");
                String nettyBackBody = CommonHelper.getNettyBackBody(terminalsXbProtocol1.getTerminalId(), valveControlData,url,communicationType);
                return success("下发命令已保存");
            }
            if(terminalsXbProtocol1.getSignPlatform() == 1){
                content.put("dataType", 2);
                content.put("payload", payload);
                jsonObject.put("content", content);
                jsonObject.put("deviceId", terminalsXbProtocol1.getDeviceId());
                jsonObject.put("ttl", 86400);
                jsonObject.put("operator", SecurityUtils.getLoginUser().getUsername());
                jsonObject.put("productId", productId);
                //发送请求
                boolean flag = terminalsXbService.sendCreateCommand(jsonObject, appKey, appSecret, masterKey);
                if (!flag) {
                    return error("发送创建命令请求时出错");
                }
                // xbCommandLogsService.saveXbCommandLog(terminalsXbProtocol.getTerminalId(),isOpen.equals("1")?1:0,"命令已成功保存到AEP平台");
                return success("命令已成功保存到AEP平台");
            }
            if (terminalsXbProtocol1.getSignPlatform() == 2){
                boolean flag = terminalsXbService.sendCreateCommandInOneNet(terminalsXbProtocol1,payload);
                if (!flag) {
                    return error("发送创建命令请求时出错");
                }
                return success("命令已成功保存到OneNet平台");
            }
            return error("发送创建命令请求时出错,请检查是否注册");
        } catch (Exception exception) {
            logger.error("系统异常",exception);
            return error("系统异常");
        }
    }

    @PostMapping("/createGuoXinDeviceInAep")
    @PreAuthorize("@ss.hasPermi('basedata:terminalxb:createGuoXinDeviceInAep')")
    public AjaxResult createGuoXinDeviceInAep(TerminalsXb terminalsXb) throws Exception {
        String sign = null;
        try {
            //根据IMEI查询设备
            List<TerminalsXb> terminalsXbs = terminalsXbService.selectTerminalsXbList(terminalsXb);
            if (terminalsXbs == null || terminalsXbs.size() == 0) {
                return error("该设备不存在");
            }
            TerminalsXb terminalsXb1 = terminalsXbs.get(0);
            if (null == terminalsXb1.getProtocolId() || !terminalsXb1.getProtocolId().equals("2")) {
                return error("协议错误，不能注册");
            }
            JSONObject responseBody = null;
            if (terminalsXb.getSignPlatform()==1){
                sign="AEP";
                responseBody = terminalsXbService.createGuoXinDeviceInAep(appKey, appSecret, masterKey, terminalsXb1);
                if (responseBody==null)
                    return error(sign+"平台注册失败");
                logger.info(String.valueOf(responseBody));
                if (Integer.parseInt(responseBody.getString("code")) == 0) {
                    String deviceId = JSONObject.parseObject(responseBody.getString("result")).getString("deviceId");
                    if(terminalsXb1.getTerminalCalibre().contains("DN")){//上面步骤转化的口径，再转回成数字，
                        String calibreValue = DictUtils.getDictValue("ldbd_pipe_caliber",terminalsXb1.getTerminalCalibre());
                        terminalsXb1.setTerminalCalibre(calibreValue);
                    }
                    terminalsXb1.setDeviceId(deviceId);
                    terminalsXbService.updateTerminalsXb(terminalsXb1);
                    return success(sign+"平台注册成功");
                }
            }
            if (terminalsXb.getSignPlatform()==2){
                sign="OneNET";
                terminalsXb1.setImsi(terminalsXb.getImsi());
                responseBody = terminalsXbService.createDeviceInOneNet(terminalsXb1);
                if (responseBody==null)
                    return error(sign+"平台注册失败");
                if (Integer.parseInt(responseBody.getString("errno")) == 0) {
                    String deviceId = responseBody.getJSONObject("data").getString("device_id");
                    terminalsXb1.setDeviceId(deviceId);
                    terminalsXbService.updateTerminalsXb(terminalsXb1);
                    return success(sign+"平台注册成功");
                }
            }
            return error(sign+"平台注册失败" + responseBody.getString("msg"));
        } catch (Exception e) {
            logger.error(ExceptionUtil.getExceptionMessage(e));
            return error("系统异常，"+sign+"平台注册失败");
        }
    }

    @Log(title = "小表管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importDeviceInAep")
    public AjaxResult importDeviceInAep(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<TerminalsXb> util = new ExcelUtil<TerminalsXb>(TerminalsXb.class);
        List<TerminalsXb> terminalsXbList = util.importExcel(file.getInputStream());
        String message = terminalsXbService.importDeviceInAep(terminalsXbList);
        return success(message);
    }

    @PostMapping("/getImportTemplate")
    public void getImportTemplate(HttpServletResponse response) throws Exception {
        ExcelUtil<TerminalXbImportantTemplate> util = new ExcelUtil<TerminalXbImportantTemplate>(TerminalXbImportantTemplate.class);
        List<TerminalXbImportantTemplate> list = Arrays.asList(TerminalXbImportantTemplate.builder().build());
        util.exportExcel(response, list, "户表档案导入模版");
    }



    @GetMapping("/updateAllLocationNb")
    public void updateAllLocationNb(){
        terminalsXbService.updateAllLocationNb();
    }


    /**
     * 表过户
     *
     * @param usersXb    新的小表用户档案
     * @param terminalId 小表id
     * @param newUser 是否新建用户
     * @return AjaxResult
     */
    @PostMapping("/changeTerminalUser/{terminalId}")
    @PreAuthorize("@ss.hasPermi('basedata:ternimalxb:changeUser')")
    public AjaxResult changeTerminalUser(@RequestBody UsersXb usersXb, @NotBlank(message = "terminalId不能为空") @PathVariable("terminalId") String terminalId, Boolean newUser) {
        if (StringUtils.isBlank(usersXb.getUserId())) {
            return error("新用户编号不能为空！");
        }
        if (newUser == null) {
            return error("请选择是否新建用户");
        } else if (newUser && StringUtils.isBlank(usersXb.getUserName())) {
            return error("新建用户用户名称不能为空！");
        }
        try {
            return toAjax(terminalsXbService.changeTerminalUser(usersXb, terminalId, newUser));
        } catch (Exception e) {
            logger.error("系统异常", e);
            return error(e.getMessage());
        }
    }

    /**
     * 批量更新小表预警策略
     *
     * @param requestBody requestBody
     * @return AjaxResult
     */
    @PostMapping("/editStrategyBatch")
    public AjaxResult editStrategy(@RequestBody String requestBody) {
        try {
            List<Long> ids = JsonUtils.getList(requestBody, "ids", Long.class);
            String strategy = JsonUtils.getString(requestBody, "strategy");
            String tenant = JsonUtils.getString(requestBody, "tenantId");
            if (CollectionUtils.isNotEmpty(ids) && StringUtils.isNotBlank(strategy)) {
                List<TerminalsXb> list = terminalsXbService.listByIds(ids);
                Set<String> tenantIdSet = list.stream().map(TerminalsXb::getTenantId).collect(Collectors.toSet());
                if (tenantIdSet.size() != 1) {
                    return error("只能为同一客户批量设置预警策略！");
                }
                String tenantId = tenantIdSet.stream().findFirst().get();
                if (!UsageRange.COMMON_FLAG.equals(strategy)) {
                    LambdaQueryWrapper<UsageRange> wrapper = Wrappers.lambdaQuery();
                    wrapper.eq(UsageRange::getTenantId, tenantId)
                            .eq(UsageRange::getStrategy, strategy)
                            .eq(UsageRange::getWarnTargetType, UsageRange.WARN_TARGET_TYPE_XB);
                    List<UsageRange> rangeList = usageRangeService.list(wrapper);
                    if (CollectionUtils.isEmpty(rangeList)) {
                        return error("该策略不适用于终端所属客户！");
                    }
                }
                List<TerminalsXb> updateList = new ArrayList<>(ids.size());
                for (Long id : ids) {
                    TerminalsXb update = new TerminalsXb();
                    update.setId(id);
                    update.setStrategy(strategy);
                    updateList.add(update);
                }
                return toAjax(terminalsXbService.updateBatchById(updateList));
            } else if (StringUtils.isNoneBlank(tenant, strategy)) {
                // 对同一个客户批量更新所有的设备策略
                if (!UsageRange.COMMON_FLAG.equals(strategy)) {
                    LambdaQueryWrapper<UsageRange> wrapper = Wrappers.lambdaQuery();
                    wrapper.eq(UsageRange::getTenantId, tenant)
                            .eq(UsageRange::getStrategy, strategy)
                            .eq(UsageRange::getWarnTargetType, UsageRange.WARN_TARGET_TYPE_XB);
                    List<UsageRange> rangeList = usageRangeService.list(wrapper);
                    if (CollectionUtils.isEmpty(rangeList)) {
                        return error("该策略不适用于终端所属客户！");
                    }
                }
                LambdaUpdateWrapper<TerminalsXb> updateWrapper = Wrappers.lambdaUpdate();
                updateWrapper.eq(TerminalsXb::getTenantId, tenant).eq(TerminalsXb::getDelFlag, 0).set(TerminalsXb::getStrategy, strategy);
                return toAjax(terminalsXbService.update(updateWrapper));
            }
            return AjaxResult.error("更新出错");
        } catch (Exception e) {
            logger.error("更新出错", e);
            return AjaxResult.error(e.toString());
        }
    }

    @PutMapping("/updateRedisCache")
    public AjaxResult updateRedisCache(@RequestBody TerminalsXb xb){
        return toAjax(terminalsXbService.updateRedisCache(xb));
    }

    @PostMapping("/getBatchUpdateTemplate")
    public void exportTemplate(HttpServletResponse response) {
        List<BatchUpdateTerminalsXb> list = Collections.singletonList(new BatchUpdateTerminalsXb());
        ExcelUtil<BatchUpdateTerminalsXb> util = new ExcelUtil<>(BatchUpdateTerminalsXb.class);
        util.exportExcel(response, list, "批量更新户表档案");
    }


    @PostMapping("/batchUpdate")
    @PreAuthorize("@ss.hasPermi('basedata:ternimalxb:batchUpdate')")
    public AjaxResult batchUpdateTerminalsXb(MultipartFile file) {
        ExcelUtil<BatchUpdateTerminalsXb> util = new ExcelUtil<>(BatchUpdateTerminalsXb.class);
        try {
            List<BatchUpdateTerminalsXb> list = util.importExcel(file.getInputStream());
            return toAjax(terminalsXbService.batchUpdateTerminalsXb(list));
        } catch (Exception e) {
            logger.error("导入批量更新户表档案数据出错", e);
            return AjaxResult.error("导入批量更新户表档案数据出错", e.toString());
        }
    }

}
